package com.wisdytech.linkdcs.equipment.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.wisdytech.common.handler.ResourceMatchingService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.common.bean.StandardTableResult;
import com.wisdytech.common.session.UserSession;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.DataTransformUtil;
import com.wisdytech.common.utils.DateUtil;
import com.wisdytech.linkdcs.equipment.model.CollectionParam;
import com.wisdytech.linkdcs.equipment.model.EquipModel;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.equipment.model.EquipmentMQ;
import com.wisdytech.linkdcs.equipment.service.IEquipmentModelService;
import com.wisdytech.linkdcs.equipment.service.IEquipmentMqService;
import com.wisdytech.linkdcs.equipment.service.IEquipmentParamService;
import com.wisdytech.linkdcs.equipment.service.IEquipmentRegisteredService;
import com.wisdytech.linkdcs.equipment.vo.EquipTaskVO;
import com.wisdytech.linkdcs.equipment.vo.EquipmentRegisterVO;
import com.wisdytech.linkdcs.equipment.vo.MqParamVO;
import com.wisdytech.linkdcs.system.model.SysUser;

/**
 * <p>
 * ClassName: EquipRegisteredAction
 * </p>
 * <p>
 * Description: 设备注册页面的action层
 * </p>
 * <p>
 * Author: kongming
 * </p>
 * <p>
 * Date: 2017-9-29
 * </p>
 */
@Controller
@RequestMapping("/equipment/register")
public class EquipRegisteredAction {
    /**
     * 注入设备注册equipmentRegisteredService
     */
    @Autowired
    @Qualifier("equipmentRegisterService")
    private IEquipmentRegisteredService equipmentRegisteredService;
    /**
     * 注入设备类别equipmentModelService
     */
    @Autowired
    @Qualifier("equipmentModelService")
    private IEquipmentModelService equipmentModelService;

    @Resource
    private IEquipmentMqService eqMqService;

    @Resource
    private IEquipmentParamService equipmentParamService;
    @Autowired
    @Qualifier("resourceMatchingService")
    private ResourceMatchingService resourceMatchingService;

    @Value("${img.localtion}")
    private String localtion;

    @RequestMapping("/index")
    public String index(Model model, String modelCode, HttpServletRequest httpRequest){
        this.resourceMatchingService.getResourceName(httpRequest,model);
        if (StringUtils.isNotBlank(modelCode)) {
            model.addAttribute("modelCode", modelCode);
        }
        return "equipment/equipRegistered/registered";
    }


    /**
     * 分页条件查询设备类别管理页面信息
     *
     * @param modelCode 设备类别编号
     * @param modelType 设备类别型号
     * @param filter    分页参数
     * @return 分页查询结果集
     */
    @RequestMapping(value = "/listEquipmentRegisterByFilter/get.mvc")
    @ResponseBody
    public StandardTableResult<EquipmentRegisterVO> listEquipmentRegisterByFilter(String modelCode, String equipCode, String equipName, Filter filter) {
        PageInfo<Equipment> equipRegisters = equipmentRegisteredService.listEquipmentRegisterByFilter(modelCode, equipCode, equipName, filter);
        //转换为前台结果集
        List<Equipment> registerList = equipRegisters.getList();
        List<EquipmentRegisterVO> registerVOList = new ArrayList<EquipmentRegisterVO>();
        for (Equipment register : registerList) {
            registerVOList.add(DataTransformUtil.changeRegisterVO(register));
        }
        return new StandardTableResult<EquipmentRegisterVO>(equipRegisters.getTotal(), registerVOList);
    }

    /**
     * 删除设备信息
     *
     * @param pkId 设备标识id
     * @return 结果对象
     */
    @RequestMapping(value = "/delEquipmentById/del.mvc")
    @ResponseBody
    public StandardResult delEquipmentById(String pkId) {
        SysUser userSession = BaseUtil.getCurrentUser();
        String loginName = userSession.getUsername();
        return equipmentRegisteredService.delEquipmentById(pkId, loginName);
    }

    /**
     * <p>Description: 保存设备对象</p>
     *
     * @param equipment 设备对象
     * @return 处理结果对象
     */
    @RequestMapping(value = "/saveEquipmentRegister/save.mvc")
    @ResponseBody
    public StandardResult saveEquipmentRegister(@RequestParam(value = "filePath") String filePath,
                                                Equipment equipment, HttpSession session, HttpServletRequest request) {
        SysUser userSession = BaseUtil.getCurrentUser();
        String loginName = userSession.getUsername();

        if (StringUtils.isNotBlank(filePath)) {
            equipment.setImage(filePath);
        }

        if (StringUtils.isBlank(equipment.getPkId())) {
            return equipmentRegisteredService.addEquipment(equipment, loginName);
        } else {
            return equipmentRegisteredService.updateEquipment(equipment, loginName);
        }
    }

    /**
     * <p>Description: 保存设备对象</p>
     *
     * @param model 设备对象
     * @return 处理结果对象
     */
    @RequestMapping(value = "/savePhoto/save.mvc")
    @ResponseBody
    public JSONObject savePhoto(@RequestParam(value = "file", required = false) MultipartFile file,
                                HttpSession session, HttpServletRequest request) {

        if (!file.isEmpty()) {
            //保留图片
//           String path = request.getSession().getServletContext().getRealPath("/");  
//           String pathReal = path.substring(0, path.lastIndexOf("webapp"))+"upload";
            String pathReal = localtion + "upload";
//           //文件位置存放在tomcat webapp根目录
            String fileName = file.getOriginalFilename();
            String[] fileNames = fileName.split("\\.");
            String realName = DateUtil.getCurDateDefaultStr() + "/" + BaseUtil.getUUID() + "." + fileNames[1];

            File targetFile = new File(pathReal, realName);

            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            //保存
            JSONObject filePath = new JSONObject();
            filePath.put("path", "upload/" + realName);
            try {
                file.transferTo(targetFile);
                return filePath;
            } catch (Exception e) {
                e.printStackTrace();
                //保存失败
                return new JSONObject();
            }
        }

        return new JSONObject();
    }

    /**
     * 通过主键id查询对应的设备信息
     *
     * @param pkId 主键id
     * @return 设备信息对象
     */
    @RequestMapping(value = "/getEquipmentRegisterById/get.mvc")
    @ResponseBody
    public EquipmentRegisterVO getEquipmentRegisterById(String pkId) {
        Equipment equipment = equipmentRegisteredService.getEquipmentRegisterById(pkId);
        EquipModel model = equipmentModelService.getEuipmentModelByEmModel(equipment.getModelCode());
        EquipmentRegisterVO registerVO = new EquipmentRegisterVO();
        registerVO = DataTransformUtil.changeRegisterVO(equipment, model);
        return registerVO;
    }

    /**
     * <p>Description:查询设备编号信息列表</p>
     *
     * @param modelId 设备id
     * @return 设备编号信息列表集合
     */
    @RequestMapping(value = "/listAllEquipmentByOperationId/get.mvc")
    @ResponseBody
    public List<Equipment> listAllEquipmentByOperationId(
            @ModelAttribute("operationId") String operationId, @ModelAttribute("search") String serach) {
        return equipmentRegisteredService.listAllEquipmentByOperationId(operationId, serach);
    }

    /**
     * 通过设备编号查询对应的设备信息
     *
     * @param equipCode 设备编号
     * @return 设备信息对象
     */
    @RequestMapping(value = "/getEquipmentByEquipCode/get.mvc")
    @ResponseBody
    public EquipmentRegisterVO getEquipmentByEquipCode(String equipCode) {
        Equipment equipment = equipmentRegisteredService.getEquipmentByEquipCode(equipCode);
        EquipmentRegisterVO registerVO = new EquipmentRegisterVO();
        if (equipment != null) {
            registerVO = DataTransformUtil.changeRegisterVO(equipment);
        }
        return registerVO;
    }

    /**
     * 通过设备编号查询对应的设备信息
     *
     * @param equipId 设备id
     * @return 设备信息对象
     */
    @RequestMapping(value = "/getEquipmentByEquipId/get.mvc")
    @ResponseBody
    public EquipmentRegisterVO getEquipmentByEquipId(String equipCode) {
        Equipment equipment = equipmentRegisteredService.getEquipmentByEquipCode(equipCode);
        EquipmentRegisterVO registerVO = new EquipmentRegisterVO();
        if (equipment != null) {
            registerVO = DataTransformUtil.changeRegisterVO(equipment);
        }
        return registerVO;
    }


    /**
     * <p>Description: 根据设备编号模糊匹配获取数据</p>
     *
     * @param equipCode
     * @return
     */
    @RequestMapping("/searchEquipmentByEquipCode/get.mvc")
    @ResponseBody
    public StandardResult searchEquipmentByCode(Filter filter, @ModelAttribute("equipCode") String equipCode) {
        PageInfo<Equipment> pageInfo =
                equipmentRegisteredService.searchEquipmentByCode(filter, equipCode);
        //判断是否是最后一页
        if (filter.getNum() >= pageInfo.getPages()) {
            return StandardResult.getFailResult("", pageInfo.getList());
        } else {
            return StandardResult.getSuccessResult(pageInfo.getList());
        }

    }


    /**
     * <p>Description: 根据设备类别id查找</p>
     *
     * @param modelId
     * @return
     */
    @RequestMapping("/listAllEquipment/get.mvc")
    @ResponseBody
    public StandardResult listAllEquipments(String modelId) {

        List<Equipment> lists =
                equipmentRegisteredService.listAllEquipment(modelId);
        return StandardResult.getSuccessResult(lists);
    }

    /**
     * <p>Description: 根据设备类别id查找</p>
     *
     * @param modelId
     * @return
     */
    @RequestMapping("/listAllEquipmentByModelCode/get.mvc")
    @ResponseBody
    public StandardResult listAllEquipmentsByCode(String modelCode) {

        List<Equipment> lists =
                equipmentRegisteredService.listAllEquipmentByModelCode(modelCode);
        return StandardResult.getSuccessResult(lists);
    }


    /**
     * 根据设备类别查找mq列表
     *
     * @param modelId
     * @return
     */
    @RequestMapping("/listAllModelMq/get.mvc")
    @ResponseBody
    public StandardResult ListAllModelMq(String modelId) {

        List<Map<String, Object>> data = new ArrayList<>();

        List<EquipmentMQ> eqMqLists =
                eqMqService.getModelMqList(modelId);

        //获取设备参数列表

        List<CollectionParam> collectionParams =
                equipmentParamService.listModelParams(modelId);

        //组合成需要数据对象

        //尚未分配
        if (eqMqLists.isEmpty()) {

            //单个节点
            Map<String, Object> oneList = new HashMap<>();
            List<MqParamVO> paramList = new ArrayList<MqParamVO>();
            for (CollectionParam param : collectionParams) {
                MqParamVO vo = new MqParamVO();
                vo.setPkId(param.getPkId());
                vo.setName(param.getParamName());
                vo.setIsSelected(false);
                paramList.add(vo);
            }
            oneList.put("name", "");
            oneList.put("data", paramList);

            data.add(oneList);
            return StandardResult.getSuccessResult(data);

        }

        Map<String, Set<String>> mqLists = new HashMap<>();
        //已分配
        for (EquipmentMQ eMq : eqMqLists) {

            Set<String> mqParamList;
            //循环出队列信息
            if (mqLists.containsKey(eMq.getMqName())) {
                mqParamList = mqLists.get(eMq.getMqName());
            } else {
                mqParamList = new HashSet<String>();
                mqLists.put(eMq.getMqName(), mqParamList);
            }
            mqParamList.add(eMq.getParamId());
        }

        //循环补充全部的参数
        Set<String> mqListKeys = mqLists.keySet();
        for (String mqListKey : mqListKeys) {
            //已经勾选的参数
            Set<String> paramIds = mqLists.get(mqListKey);

            //单个节点
            Map<String, Object> oneList = new HashMap<>();
            List<MqParamVO> paramList = new ArrayList<MqParamVO>();
            for (CollectionParam param : collectionParams) {
                MqParamVO vo = new MqParamVO();
                vo.setPkId(param.getPkId());
                vo.setName(param.getParamName());
                vo.setIsSelected(paramIds.contains(param.getPkId()));
                paramList.add(vo);
            }
            oneList.put("name", mqListKey);
            oneList.put("data", paramList);

            data.add(oneList);
        }


        return StandardResult.getSuccessResult(data);
    }


    @RequestMapping("/saveModelMq/save.mvc")
    @ResponseBody
    public StandardResult saveModelMq(@ModelAttribute("data") String data) {

        //解析保存mq队列
        JSONObject object = JSON.parseObject(data);

        //设备类别ID
        String modelId = object.getString("modelId");

        //参数对应的信息
        List<EquipmentMQ> params = new ArrayList<>();

        List<String> mqDatas = JSON.parseArray(object.getString("data"), String.class);
        //进行队列保存
        for (String mqData : mqDatas) {
            //多个队列
            String[] mqDataStrs = mqData.split(";");
            //队列名称
            String mqName = mqDataStrs[0];
            //队列参数列表
            String mqStrs = mqDataStrs[1];
            mqStrs.substring(0, mqStrs.length() - 1);
            String[] paramIdsArray = mqStrs.split(",");

            for (String paramId : paramIdsArray) {
                EquipmentMQ eMq = new EquipmentMQ();
                eMq.setModelId(modelId);
                eMq.setMqName(mqName);
                eMq.setParamId(paramId);
                eMq.setPkId(UUID.randomUUID().toString());
                params.add(eMq);
            }
        }

        //调用接口保存

        eqMqService.insert(modelId, params);

        return StandardResult.getSuccessResult();
    }

    /**
     * 分页查询 设备参数
     *
     * @param search 参数名称匹配
     * @param page   页面数
     * @param size   每页大小
     * @return 设备类别对应的参数列表
     */
    @RequestMapping("/listModelParams/get.mvc")
    @ResponseBody
    public StandardResult listModelParams(@ModelAttribute("modelId") String modelId) {

        List<Map<String, Object>> data = new ArrayList<>();
        List<CollectionParam> collectionParams =
                equipmentParamService.listModelParams(modelId, "", 1, Integer.MAX_VALUE);

        //单个节点
        Map<String, Object> oneList = new HashMap<>();
        List<MqParamVO> paramList = new ArrayList<MqParamVO>();
        for (CollectionParam param : collectionParams) {
            MqParamVO vo = new MqParamVO();
            vo.setPkId(param.getPkId());
            vo.setName(param.getParamName());
            vo.setIsSelected(false);
            paramList.add(vo);
        }
        oneList.put("name", "");
        oneList.put("data", paramList);

        data.add(oneList);
        return StandardResult.getSuccessResult(data);


    }

    /**
     * <p>Description: 根据设备类别id查找</p>
     *
     * @param modelId
     * @return
     */
    @RequestMapping("/equipCodeChangeByeqCode/get.mvc")
    @ResponseBody
    public StandardResult equipCodeChangeByeqCode(String equipCode) {
        Equipment equipment = equipmentRegisteredService.equipCodeChangeByeqCode(equipCode);
        if(equipment!=null){
            EquipTaskVO equipTaskVO = new EquipTaskVO();
            equipTaskVO.setAreaName(equipment.getAreaName());
            equipTaskVO.setEquipName(equipment.getEquipName());
            equipTaskVO.setFatoryName(equipment.getFatoryName());
            equipTaskVO.setLineName(equipment.getLineName());
            equipTaskVO.setShopName(equipment.getShopName());
            return StandardResult.getSuccessResult(equipTaskVO);
        }
        return StandardResult.getSuccessResult(new EquipTaskVO());
    }


}
